#include "peakbar.h"
#include "dm/dmdef.h"

#include <QLinearGradient>


PeakBar::PeakBar(QWidget *parent)
    : AWidget{parent}
    , m_peak{0}
{
    setMinimumSize(40, 150);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}

void PeakBar::peak(const uint8_t &value)
{
    m_peak = value;
    update();
}

void PeakBar::paintEvent(QPaintEvent *event)
{
    QWidget::paintEvent(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);

    auto pen = painter.pen();
    pen.setWidth(1);

    // 刻度
    const double w = width() * 0.6;
    const double h = static_cast<double>(height()) / (PEAK_SCALE_LENGTH / PEAK_SCALE_STEP + 1);
    for (int i = PEAK_SCALE_MAX; i >= PEAK_SCALE_MIN; i -= PEAK_SCALE_STEP) {
        QRectF tRect(0, (PEAK_SCALE_MAX - i) / PEAK_SCALE_STEP * h, w, h);
        if (i % (PEAK_SCALE_STEP * 2) == 0) {
            painter.drawLine(QPointF(width() * 0.62, tRect.center().y()), QPointF(width() * 0.70, tRect.center().y()));
            painter.drawText(tRect, Qt::AlignRight | Qt::AlignVCenter, QString::number(i));
        }
        else {
            painter.drawLine(QPointF(width() * 0.66, tRect.center().y()), QPointF(width() * 0.70, tRect.center().y()));
        }
    }
    // limiter
    QRectF lRect(1, 1, width() * 0.2, width() * 0.2);
    if (m_peak & 0x80) {
        painter.setPen(QColor(255, 0, 0));
        painter.setBrush(QColor(255, 0, 0));
    }
    else {
        painter.setPen(QColor(82, 204, 20));
        painter.setBrush(QColor(82, 204, 20));
    }
    painter.drawEllipse(lRect);
    // 进度条
    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(94, 99, 107));

    QRectF bRect(width() * 0.76, 0, width() * 0.20, height());

    QLinearGradient gradient(bRect.topLeft(), bRect.bottomRight());
    // gradient.setColorAt(0.0, QColor(255, 0, 0, 64));
    // gradient.setColorAt(0.1, QColor(255, 212, 0, 64));
    // gradient.setColorAt(1.0, QColor(82, 204, 20, 64));

    // painter.setBrush(gradient);

    painter.drawRoundedRect(bRect, 6, 6);
    // 进度
    int value = (m_peak & 0x7F) + PEAK_MIN;
    if (value >= PEAK_SCALE_MIN) {
        // QLinearGradient gradient(bRect.topLeft(), bRect.bottomRight());
        gradient.setColorAt(0.0, QColor(255, 0, 0));
        gradient.setColorAt(0.1, QColor(255, 212, 0));
        gradient.setColorAt(1.0, QColor(82, 204, 20));

        painter.setBrush(gradient);

        double vh = static_cast<double>(value - PEAK_SCALE_MIN) / PEAK_SCALE_LENGTH * (bRect.height() - h) + h / 2;
        if (value > PEAK_SCALE_MAX) {
            vh = bRect.height();
        }
        painter.drawRoundedRect(QRectF(bRect.x(), bRect.bottomLeft().y() - vh, bRect.width(), vh), 6, 6);
    }
}
